﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace 测试瞬间输入字符
{
    public partial class MainWindow : Window
    {
        private StringBuilder inputBuffer = new StringBuilder();
        private DispatcherTimer resetTimer;
        private DateTime firstKeyTime;
        private DateTime lastKeyTime;

        // 扫码枪判定参数
        private const int RequiredLength = 12;          // 必须12位字符
        private const int MaxTotalTimeMs = 500;         // 总输入时间不超过500ms
        private const int MaxKeyIntervalMs = 100;       // 按键间隔不超过100ms

        public MainWindow()
        {
            InitializeComponent();

            resetTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(MaxKeyIntervalMs)
            };
            resetTimer.Tick += ResetTimer_Tick;
        }

        private void ScanTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // 忽略系统按键
            if (e.Key == Key.LeftShift || e.Key == Key.RightShift ||
                e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl ||
                e.Key == Key.LeftAlt || e.Key == Key.RightAlt ||
                e.Key == Key.LWin || e.Key == Key.RWin)
            {
                return;
            }

            // 获取按键字符
            char keyChar = GetCharFromKey(e.Key, Keyboard.Modifiers);
            if (keyChar == '\0') return;

            // 记录时间
            DateTime currentTime = DateTime.Now;

            // 检查是否是新的输入
            if (inputBuffer.Length == 0)
            {
                firstKeyTime = currentTime;
                StatusTextBlock.Text = "正在接收扫码...";
            }
            else
            {
                // 检查按键间隔
                TimeSpan interval = currentTime - lastKeyTime;
                if (interval.TotalMilliseconds > MaxKeyIntervalMs)
                {
                    // 间隔过长，重置
                    ResetInput();
                    StatusTextBlock.Text = "输入中断，重新开始";
                    return;
                }
            }

            lastKeyTime = currentTime;
            inputBuffer.Append(keyChar);

            // 重置超时计时器
            resetTimer.Stop();
            resetTimer.Start();

            // 更新状态显示
            StatusTextBlock.Text = $"已接收: {inputBuffer.Length}/{RequiredLength}";

            // 检查是否达到12位
            if (inputBuffer.Length == RequiredLength)
            {
                ProcessBarcodeInput();
            }

            e.Handled = true; // 防止字符显示在文本框中
        }

        private void ResetTimer_Tick(object sender, EventArgs e)
        {
            // 超时没有新输入，重置
            resetTimer.Stop();
            if (inputBuffer.Length > 0 && inputBuffer.Length < RequiredLength)
            {
                StatusTextBlock.Text = "输入超时，重新开始";
                ResetInput();
            }
        }

        private void ProcessBarcodeInput()
        {
            resetTimer.Stop();

            // 计算总耗时
            TimeSpan totalTime = lastKeyTime - firstKeyTime;

            if (totalTime.TotalMilliseconds <= MaxTotalTimeMs)
            {
                string barcode = inputBuffer.ToString();
                StatusTextBlock.Text = $"扫码成功: {barcode}";
                ResultListBox.Items.Add($"[{DateTime.Now:HH:mm:ss.fff}] {barcode}");

                // 处理扫码结果
                HandleBarcode(barcode);

                // 显示在文本框中
                ScanTextBox.Text = barcode;
            }
            else
            {
                StatusTextBlock.Text = "输入太慢，不是有效的扫码";
            }

            ResetInput();
        }

        private void ResetInput()
        {
            inputBuffer.Clear();
        }

        private void HandleBarcode(string barcode)
        {
            // 这里添加你的业务逻辑
            // 例如：验证条码、查询数据库、提交表单等
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            ResultListBox.Items.Clear();
            ScanTextBox.Text = string.Empty;
            StatusTextBlock.Text = "等待扫码...";
            ResetInput();
        }

        private char GetCharFromKey(Key key, ModifierKeys modifiers)
        {
            // 将按键转换为字符
            int virtualKey = KeyInterop.VirtualKeyFromKey(key);
            char c = '\0';

            if (virtualKey >= 48 && virtualKey <= 57) // 数字键
            {
                c = (char)(modifiers.HasFlag(ModifierKeys.Shift)
                    ? GetShiftedDigit((char)virtualKey)
                    : (char)virtualKey);
            }
            else if (virtualKey >= 65 && virtualKey <= 90) // 字母键
            {
                c = modifiers.HasFlag(ModifierKeys.Shift)
                    ? (char)virtualKey
                    : (char)(virtualKey + 32); // 转换为小写
            }
            else
            {
                // 其他键可以根据需要扩展
                switch (key)
                {
                    case Key.OemMinus:
                        c = modifiers.HasFlag(ModifierKeys.Shift) ? '+' : '-';
                        break;
                    case Key.OemPlus:
                        c = modifiers.HasFlag(ModifierKeys.Shift) ? '=' : '+';
                        break;
                        // 添加更多按键映射...
                }
            }

            return c;
        }

        private char GetShiftedDigit(char digit)
        {
            // 处理数字键上的符号（如 Shift+1 = !）
            switch (digit)
            {
                case '1': return '!';
                case '2': return '@';
                case '3': return '#';
                case '4': return '$';
                case '5': return '%';
                case '6': return '^';
                case '7': return '&';
                case '8': return '*';
                case '9': return '(';
                case '0': return ')';
                default: return digit;
            }
        }
    }
}